// Common/ListFileUtils.cpp

#include "StdAfx.h"

//#include "Common/MyWindows.h"
#include "Common/Stream/FileIO.h"

#include "ListFileUtils.h"
#include "Common/String/StringConvert.h"
#include "Common/String/UTFConvert.h"

static const TCHAR kQuoteChar     = _T('\"');
static void RemoveQuote(CString &s)
{
  if (s.GetLength() >= 2)
    if (s[0] == kQuoteChar && s[s.GetLength() - 1] == kQuoteChar)
      s = s.Mid(1, s.GetLength() - 2);
}

bool ReadNamesFromListFile(LPCTSTR fileName, CStringVector &resultStrings, UINT codePage)
{
  Common::IO::CInFile file;
  if (!file.Open(fileName))
    return false;
  UINT64 length;
  if (!file.GetLength(length))
    return false;
  if (length > ((UINT32)1 << 31))
    return false;
  CString s;
  TCHAR *p = s.GetBuffer((int)length + 1);
  UINT32 processed;
  if (!file.Read(p, (UINT32)length, processed))
    return false;
  p[(UINT32)length] = 0;
  s.ReleaseBuffer();
  file.Close();

  CString u(s);
	//TODO: removed by me
  /*#ifdef CP_UTF8
  if (codePage == CP_UTF8)
  {
    if (!ConvertUTF8ToUnicode(s, u))
      return false;
  }
  else
  #endif
    u = MultiByteToUnicodeString(s, codePage);
  if (!u.IsEmpty())
  {
    if (u[0] == 0xFEFF)
      u.Delete(0);
  }
	*/
  CString t;
  for (int i = 0; i < u.GetLength(); i++)
  {
    TCHAR c = u[i];
    if (c == _T('\n') || c == 0xD) //TODO: change character from UNICODE
    {
      t.Trim();
      RemoveQuote(t);
      if (!t.IsEmpty())
		  resultStrings.push_back(t);
      t.Empty();
    }
    else
      t += c;
  }
  t.Trim();
  RemoveQuote(t);
  if (!t.IsEmpty())
	  resultStrings.push_back(t);
  return true;
}
